import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.StringTokenizer;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

public class ScoreTable extends JTable implements MouseListener {

	private static final long serialVersionUID = 1L;
	
	DefaultTableModel tabeliMudel;
	YahtzeeClient client;
	int[] jubaValitud;
	int totalPlayers;
	
	ScoreTable(YahtzeeClient client) {
		this.tabeliMudel = initialTable();
		this.jubaValitud = new int[17];
		this.client = client;
		setModel(tabeliMudel);
		setFillsViewportHeight(true);
		setGridColor(Color.BLACK);
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.setColumnSelectionAllowed(false);
		this.setBounds(getWidth()/2, getHeight()/2, getWidth()/2, getHeight()/2);
		addMouseListener(this);
		setEnabled(false);
	}
	
	public DefaultTableModel initialTable() {
		
		DefaultTableModel model = new DefaultTableModel();
		
		Object[] comboColumn = {
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "Boonus",
                "Paar",
                "Kolmik",
                "Nelik",
                "Kaks paari",
                "Maja",
                "Väike rida",
                "Suur rida",
                "Summa",
                "Yahtzee",
                "Kokku"
                }; 
		
		model.addColumn("Kombod", comboColumn);
		
		return model;
	}
	
	void createTable(StringTokenizer input) {
		
		input.nextToken(); // "players"
		while (input.hasMoreTokens()) {	
			tabeliMudel.addColumn(input.nextToken());
			totalPlayers++;
		}
	}
	
	void updateTable(StringTokenizer input) {
		
		String readValue;
		
		for (int i = 1; i <= totalPlayers; i++) {
			
			input.nextToken(); // player name
			for(int j = 0; j<17; j++) {
				readValue=input.nextToken();
				if (readValue.equals("0")) {
					setValueAt(null, j, i);
				} else if (readValue.equals("-1")) {
					setValueAt("0", j, i);
				} else {
					setValueAt(readValue, j, i);
				}
			}	
		}	
	}

	public void mouseClicked(MouseEvent e) {

			JTable target = (JTable)e.getSource();
			int row = target.getSelectedRow();
			if (row != 6 && row != 16 && jubaValitud[row] == 0) { // "boonus" ja "kokku" valimine ei tee midagi, 
																//võib ka error popupi teha
				jubaValitud[row] = 1;
				setEnabled(false);
				client.io.send(Integer.toString(row));		
		}
	}

	public void mouseEntered(MouseEvent arg0) {}
	public void mouseExited(MouseEvent arg0) {}  // neid pole vaja..	
	public void mousePressed(MouseEvent arg0) {}
	public void mouseReleased(MouseEvent arg0) {}
	
}
